import 'package:flutter/material.dart';
import 'package:flutter_getx/core/utils/device_utils.dart';
import 'package:flutter_getx/res/colors/colors.dart';
import 'package:flutter_getx/res/dimens/dimens.dart';

class TextGradientColorWidget extends StatefulWidget {
  final String data;
  final List<Color> colors;
  final TextStyle? style;

  const TextGradientColorWidget(this.data, {Key? key, this.colors = const [gradientStart, gradientEnd], this.style}) : super(key: key);

  @override
  _TextGradientColorState createState() => _TextGradientColorState();
}

class _TextGradientColorState extends State<TextGradientColorWidget> {

  TextStyle? style;
  WidgetsBinding? widgetsBinding = WidgetsBinding.instance;

  @override
  void initState() {
    super.initState();

    widgetsBinding?.addPostFrameCallback((timeStamp) {
      if(!Device.isWeb) {
        final RenderBox? box = context.findRenderObject() as RenderBox?;
        var left = 0.0;
        var width = 0.0;
        if (box != null) {
          final topLeftPosition = box.localToGlobal(Offset.zero);
          final size = box.size;
          left = topLeftPosition.dx;
          width = size.width;
          setState(() {
            style = TextStyle(
                fontSize: widget.style?.fontSize ?? Sp.sp12,
                fontWeight: widget.style?.fontWeight,
                foreground: Paint()
                  ..shader =
                  LinearGradient(colors: widget.colors, stops: const [0.3, 0.8])
                      .createShader(Rect.fromLTWH(left, 0, width, 0)));
          });
        }
      } else{
        setState(() {
          style = TextStyle(
            fontSize: widget.style?.fontSize ?? Sp.sp12,
            fontWeight: widget.style?.fontWeight,
            color: widget.colors[1],
          );
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Text(widget.data, style: style);
  }
}
